var fInspector = {
	id : "finspector@itamt.org",
	path : "",
	isOn : false,
	preTab : null,
	onFirefoxLoad : function(evt) {
		fInspector.trace('onFirefoxLoad...');

		var fpVersion = getFlashPluginVersion();
		if (fpVersion.major > 9) {
			fInspector.setPreloadSwf(fInspector
					.getAddonFilePath("/content/tInspectorPreloader.swf"));
			fInspector.setPathFlashTrust(fInspector
					.getAddonFilePath("/content/"));

			gBrowser.browsers.forEach(function(browser) {
				fInspector.toggleProgressListener(browser.webProgress, true);
			}, fInspector);

			gBrowser.tabContainer.addEventListener("TabOpen",
					fInspector.handleEvent, false);
			gBrowser.tabContainer.addEventListener("TabClose",
					fInspector.handleEvent, false);

			gBrowser.addEventListener("DOMContentLoaded", function(event) {
				var doc = event.originalTarget;
				if (doc instanceof HTMLDocument) {
					doc.defaultView.addEventListener("unload", function() {
						fInspector.onPageUnload(doc);
					}, true);
				}
			}, true);

			gBrowser.addEventListener("load", function(event) {
				var doc = event.originalTarget;
				if (doc instanceof HTMLDocument) {
					fInspector.onPageLoad(doc);
				}
			}, true);

			gBrowser.tabContainer.addEventListener("TabSelect",
					fInspector.onTabSelect, false);
		} else {
			fInspector.showNeedDebuggerFP();
		}
	},

	// 关闭Firefox时
	onFirefoxUnLoad : function(evt) {
		// 清除mm.cfg中PreloadSWF的设置
		fInspector.clearPreloadSwf(fInspector
				.getAddonFilePath("/content/tInspectorPreloader.swf"));

		gBrowser.browsers.forEach(function(browser) {
			fInspector.toggleProgressListener(browser.webProgress, false);
		}, fInspector.progressListener);

		gBrowser.tabContainer.removeEventListener("TabOpen",
				fInspector.handleEvent, false);
		gBrowser.tabContainer.removeEventListener("TabClose",
				fInspector.handleEvent, false);
	},

	toggleProgressListener : function(aWebProgress, aIsAdd) {
		if (aIsAdd) {
			aWebProgress.addProgressListener(fInspector.progressListener,
					aWebProgress.NOTIFY_ALL);
		} else {
			aWebProgress.removeProgressListener(fInspector.progressListener);
		}
	},

	handleEvent : function(aEvent) {
		let
		tab = aEvent.target;
		let
		webProgress = gBrowser.getBrowserForTab(tab).webProgress;
		fInspector.toggleProgressListener(webProgress,
				("TabOpen" == aEvent.type));
	},

	onTabSelect : function(evt) {
		fInspector.trace("onTabSelect");
		// --------tInspectorMonitor中的所有连接 ------------
		document.getElementById('tInspectorController').clearAllConnections();

		// --------tInspectorMonitor连接当前tab中的swf--------
		var doc = gBrowser.selectedBrowser.contentDocument;
		if (doc.embeds) {
			for ( var i = 0; i < doc.embeds.length; i++) {
				try {
					var embed = doc.wrappedJSObject.embeds[i];
					fInspector.trace("connectController: " + embed.id);
					embed.connectController();
				} catch (error) {
					// fInspector.trace(error.message);
				}
			}
			fInspector.callInspector();
		}
	},

	/**
	 * param doc HTMLDocument
	 */
	onPageLoad : function(doc) {
		fInspector.trace("onPageLoad");
		if (doc == gBrowser.selectedBrowser.contentDocument) {
			fInspector.trace("the doc is in current tab");
			setTimeout(function() {
				if (doc.embeds) {
					for ( var i = 0; i < doc.embeds.length; i++) {
						try {
							var embed = doc.wrappedJSObject.embeds[i];
							fInspector.trace("connectController: " + embed.id);
							embed.connectController();
						} catch (error) {
							// fInspector.trace(error.message);
				}
			}
		}
		fInspector.callInspector();
	}, 1000	);
		}
	},

	onPageUnload : function(doc) {
		for ( var i = 0; i < doc.embeds.length; i++) {
			try {
				fInspector.trace("disconnectController: " + embed.id);
				var embed = doc.wrappedJSObject.embeds[i];
				embed.disconnectController();
			} catch (error) {
			}
		}
	},

	toggleInspector : function() {
		fInspector.isOn = !fInspector.isOn;
		fInspector.callInspector();
	},

	callInspector : function() {
		fInspector.trace("callInspector");
		if (fInspector.isOn) {
			document.getElementById('finspectorBtnImg').setAttribute("state",
					"on");
			document.getElementById('tInspectorController').startInspector();
		} else {
			document.getElementById('finspectorBtnImg').setAttribute("state",
					"off");
			document.getElementById('tInspectorController').stopInspector();
		}
	},
	// 设置mm.cfg中的PreloadSWF值
	setPreloadSwf : function(file) {
		var mmcfg = FileIO.open(Util.getMMCfgPath());
		if (!mmcfg.exists()) {
			fInspector.trace('the mm.cfg file dose not exist, we create it.');
			FileIO.create(mmcfg);
		}

		var data = FileIO.read(mmcfg);
		var preloadSwfPath = "PreloadSWF=" + file;
		if (data.indexOf(preloadSwfPath) >= 0) {
			fInspector.trace('the PreloadSWF already be:' + file);
		} else {
			if (data.match(/PreloadSWF=.*\.swf/)) {
				data = data.replace(/PreloadSWF=.*.swf/, preloadSwfPath);
				fInspector.trace('replace preloadswf path: ' + data);
			} else {
				data += '\r' + preloadSwfPath;
				fInspector.trace('add preloadswf path: ' + data);
			}

			FileIO.write(mmcfg, data);
		}
	},

	clearPreloadSwf : function(file) {
		var mmcfg = FileIO.open(Util.getMMCfgPath());
		if (!mmcfg.exists()) {
			fInspector
					.trace('the mm.cfg file dose not exist, we donot need to clear the PreloadSWF config.');
			return;
		}

		var data = FileIO.read(mmcfg);
		var preloadSwfPath = "PreloadSWF=" + file;
		if (data.indexOf(preloadSwfPath) >= 0) {
			data = data.replace(preloadSwfPath, "");
			FileIO.write(mmcfg, data);
			fInspector.trace('the PreloadSWF has been clear!');
		} else {
			fInspector
					.trace('the PreloadSWF reference other swf, so we donot need to clear it.');
		}
	},

	// 把文件路径添加到Flash Player的信任路径
	setPathFlashTrust : function(path) {
		var cfg = FileIO.open(Util.getFinspectorTrustPath());
		if (!cfg.exists()) {
			var cfgCreated = FileIO.create(cfg);
			fInspector.trace('the cfg doesnot exist, create it: ' + cfgCreated);
		}

		var data = FileIO.read(cfg);
		if (data.indexOf(path) < 0) {
			fInspector.trace('add path::' + path + ':: to cfg.');
			FileIO.write(cfg, "\n" + path + "\n");
		} else {
			fInspector.trace('the path has been in cfg.');
		}
	},

	// 得到fInspector下文件的系统路径
	getAddonFilePath : function(relativePath) {
		relativePath = relativePath.replace(/\//g, Util.PATH_SEP);
		return fInspector.path + relativePath;
	},

	// 如果Debugger Flash Player没有安装
	showNeedDebuggerFP : function() {
		document.getElementById("needFlashPlayerPanel").openPopup(
				document.getElementById("finspectorStatusBarBtn"),
				"before_start", 60, 50, false, false);
		// window.openDialog("chrome://finspector/content/needDebuggerFP.xul");
	},

	// 测试输出
	trace : function(obj) {
		dump('\n' + obj);
	},

	progressListener : {

		QueryInterface : function(aIID) {
			if (aIID.equals(Components.interfaces.nsIWebProgressListener)
					|| aIID
							.equals(Components.interfaces.nsISupportsWeakReference)
					|| aIID.equals(Components.interfaces.nsISupports))
				return this;
			throw Components.results.NS_NOINTERFACE;
		},

		onStateChange : function(aWebProgress, aRequest, aFlag, aStatus) {
			// If you use myListener for more than one tab/window, use
			// aWebProgress.DOMWindow to obtain the tab/window which triggers
			// the
			// state
			// change
			// if ((aStateFlags & Ci.nsIWebProgressListener.STATE_START) &&
			// (aStateFlags
			// & Ci.nsIWebProgressListener.STATE_IS_DOCUMENT)) {
			if ((aFlag & Components.interfaces.nsIWebProgressListener.STATE_START)
					&& (aFlag & Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT)) {
				// This fires when the load event is initiated
				fInspector.trace("This fires when the load event is initiated");
				fInspector.setPreloadSwf(fInspector
						.getAddonFilePath("/content/tInspectorPreloader.swf"));
			} else if ((aFlag & Components.interfaces.nsIWebProgressListener.STATE_STOP)
					&& (aFlag & Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT)) {
				// This fires when the load finishes
				fInspector.trace("This fires when the load finishes");
				// 清除mm.cfg中PreloadSWF的设置
				fInspector.clearPreloadSwf(fInspector
						.getAddonFilePath("/content/tInspectorPreloader.swf"));
			}
		},

		onLocationChange : function(aProgress, aRequest, aURI) {
			// This fires when the location bar changes; i.e load event is
			// confirmed
			// or when the user switches tabs. If you use myListener for more
			// than
			// one
			// tab/window,
			// use aProgress.DOMWindow to obtain the tab/window which triggered
			// the
			// change.
		},

		onProgressChange : function(aWebProgress, aRequest, curSelf, maxSelf,
				curTot, maxTot) {
		},
		onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) {
		},
		onSecurityChange : function(aWebProgress, aRequest, aState) {
		}
	}
};

fInspector.path = Components.classes["@mozilla.org/extensions/manager;1"]
		.getService(Components.interfaces.nsIExtensionManager)
		.getInstallLocation(fInspector.id).getItemFile(fInspector.id,
				"install.rdf").parent.path;
fInspector.setPreloadSwf(fInspector
		.getAddonFilePath("/content/tInspectorPreloader.swf"));
fInspector.setPathFlashTrust(fInspector.getAddonFilePath("/content/"));

window.addEventListener('load', fInspector.onFirefoxLoad, false);
window.addEventListener('unload', fInspector.onFirefoxUnLoad, false);
